<?php

class Db_Tables2_BContractSku
{
	function __construct() {
		$this->dealers_db = Zend_Registry::get("dealers_db");
	}
	
	function GetProductId($contract_id)
	{
		$result = NULL;
		
		$select = $this->dealers_db->select();
		$select->from("b_contract_sku", array("product_id"));
		$select->where("contract_id = ?", $contract_id);
		$row = $this->dealers_db->fetchRow($select);
		
		if($row)
		{
			$result = $row['product_id'];
		}
		
		return $result;
	}
	
	function UpdateInvoiceApplied($cs_id, $type, $value) //$type 1=增加开票申请 2=驳回开票申请
	{
		$result = array(
			"result" => FALSE,
			"contract_id" => 0,
			"invoice_done" => -1
		);
		
		$select = $this->dealers_db->select();
		$select->from("b_contract_sku", array("contract_id", "invoice_applied"));
		$select->where("cs_id = ?", $cs_id);
		$row = $this->dealers_db->fetchRow($select);
		
		if($row)
		{
			if(1 == $type)
			{
				$invoice_applied = $row['invoice_applied'] + $value;
			}else{
				$invoice_applied = $row['invoice_applied'] - $value;
			}
			
			$set = array("invoice_applied" => $invoice_applied);
			$where = "cs_id = ".$cs_id;
			
			$this->dealers_db->update("b_contract_sku", $set, $where);
			
			$result['result'] = TRUE;
			$result['contract_id'] = $row['contract_id'];
			
			$refresh_result = $this->RefreshInvoiceDone($result['contract_id']);
			
			if($refresh_result['result'])
			{
				$result['invoice_done'] = $refresh_result['invoice_done'];
			}
		}
		
		return $result;
	}
	
	function RefreshInvoiceDone($contract_id)
	{
		$result = array(
			"result" => FALSE,
			"invoice_done" => -1
		);
		
		$select = $this->dealers_db->select();
		$select->from("b_contract_sku", array("actual_pay", "invoice_applied"));
		$select->where("contract_id = ?", $contract_id);
		$rows = $this->dealers_db->fetchAll($select);

		if($rows)
		{
			$result['result'] = TRUE;
			
			$total_applied = $total = 0;

			foreach($rows as $row)
			{
				$total_applied += $row['invoice_applied'];
				$total += $row['actual_pay'];
			}

			if($total_applied >= $total)
			{
				$select = $this->dealers_db->select();
				$select->from("b_contract_invoice", array("id"));
				$select->where("contract_id = ?", $contract_id);
				$select->where("status = ?", 1);
				$row = $this->dealers_db->fetchRow($select);

				if($row)
				{
					$result['invoice_done'] = 2;
				}else{
					$result['invoice_done'] = 3;
				}
			}elseif(0 == $total_applied)
			{
				$result['invoice_done'] = 0;
			}else{
				$result['invoice_done'] = 1;
			}
		}
		
		return $result;
	}
}